package cn.com.yang.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.util.TrustManagerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;

import cn.com.yang.utils.DateUtil;
import cn.com.yang.utils.RSAUtil;


/**
 * 礼品请求封装
 * @author devdt142
 * @time 2022年3月10日-下午5:03:49
 */

public class HTTPGiftProxy {
	private static Logger logger = LoggerFactory.getLogger(HTTPGiftProxy.class);
	/**
	 * 代理IP
	 */
	private static String prxoy_host;
	@Value("${PRXOY_HOST}")
	public void setProxyHost(String host) {
		HTTPGiftProxy.prxoy_host=host;
	}
	/**
	 * 代理端口
	 */
	private static int proxy_port;
	@Value("${PROXY_PORT}")
	public void setProxyPort(int port) {
		HTTPGiftProxy.proxy_port=port;
	}
	/**
	 * 第三方请求接口
	 * @param url 
	 * @param orderInfo
	 * @param mchtInfo
	 * @param ctx
	 * @return 响应信息
	 * @throws Exception 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String post(String url, Map parmas, Map mchtInfo){
		logger.info("对方接口地址:{}",url);
		boolean https=false;
		if(!StringUtils.isEmpty(url)) {
			if(url.startsWith("https")) {
				https=true;
			}
		}
		HttpURLConnection httpConn=null;
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			URL urlClient = new URL(url);
			//HTTPS双向认证
			if(https) {
				InetSocketAddress addr = new InetSocketAddress(prxoy_host, proxy_port);
				Proxy proxy = new Proxy(Type.HTTP, addr);
				TrustManager[] tm= {TrustManagerUtils.getAcceptAllTrustManager()};
				SSLContext sslContext=SSLContext.getInstance("SSL", "SunJSSE");
				sslContext.init(null, tm, new java.security.SecureRandom());
				SSLSocketFactory ssf=sslContext.getSocketFactory();
				// 忽略域名验证（不安全）
//				HostnameVerifier hostnameVerifier = new HostnameVerifier() {
//	                @Override
//	                public boolean verify(String hostname, SSLSession session) {
//	                    logger.info("hostname: {},SSLSession:{}",hostname , session);
//	                    if(!StringUtil.isBlank(hostname)){
//	                        if ("域名".equals(hostname)) {
//	                            return true;
//	                        } else {
//	                            boolean verify = HttpsURLConnection.getDefaultHostnameVerifier().verify("域名", session);
//	                            return verify;
//	                        }
//	                    }else{
//	                        return false;
//	                    }
//                	}
//				};
//				HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
				HttpsURLConnection httpsConn = (HttpsURLConnection) urlClient.openConnection(proxy);
				httpsConn.setSSLSocketFactory(ssf);
				httpConn=httpsConn;
			}else {
				httpConn = (HttpURLConnection) urlClient.openConnection();
			}
			httpConn.setRequestMethod(HttpMethod.POST.name());
			// 创建连接超时时间
			httpConn.setConnectTimeout(Integer.valueOf((String) mchtInfo.get("CON_TIMEOUT")));
			// 响应超时时间
			httpConn.setReadTimeout(Integer.valueOf((String) mchtInfo.get("RESP_TIMEOUT")));
			httpConn.setRequestProperty("Connection", "keep-alive");
			httpConn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
			httpConn.setRequestProperty("Content-Type", "application/json");
			httpConn.setRequestProperty("Accept", "application/json");
			/**
			 * TranChan交易渠道String是固定值HBMINI
			 * TranTime交易时间戳String是yyyyMMddHHmmss
			 * TranSign[授权码:商户号:报文体我方订单编号]
			 */
			httpConn.setRequestProperty("TranChan", "HBMINI");
			httpConn.setRequestProperty("TranTime", DateUtil.parseDate(new Date(), "yyyyMMddHHmmss"));
			httpConn.setRequestProperty("TranSign", 
					DigestUtils.sha1Hex(mchtInfo.get("AUTH_KE")+":"+mchtInfo.get("MCHT_ID")+":"+parmas.get("OrderId")));
			httpConn.setDoInput(true);
			//设置为true之后，请求方法将会由GET编程POST
			//GET仅仅限于安全操作(修改或者创建属于不安全的操作)
			httpConn.setDoOutput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(httpConn.getOutputStream());
			// 发送请求参数
			Map data = new HashMap();
			//判断是否RSA加密
			if("1".equals(mchtInfo.get("IF_ENCRYPT"))) {
				data.put("Data", RSAUtil.encrypt(JSON.toJSONString(parmas), (String)mchtInfo.get("RSA_PUBKEY"), "UTF-8"));
			}else {
				data.put("Data", parmas);
			}
			logger.info("请求体信息:[{}]",JSON.toJSONString(data));
			out.print(JSON.toJSONString(data));
			out.flush();
			int code = httpConn.getResponseCode();		
			if(code >= 200 && code< 300) {
				in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF_8"));
			}else {
				throw new YangRuntimeException("WXMN-3-007004",String.format("响应异常，响应code:%s", code));
			}
			StringBuffer sb = new StringBuffer();
			String line;
			boolean firstLine = true;
			while ((line = in.readLine()) != null) {
				if (firstLine) {
					firstLine = false;
				} else {
					sb.append("\n");
				}
				sb.append(line);
			}
			return sb.toString();
		} catch (Exception e) {
			logger.error("请求异常：", e);
		} finally {
			// 关闭流
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(in);
		}
		return null;
	}
}
